package com.finalab.yueqiu.util.communicate;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import javax.net.ssl.SSLContext;
import java.security.NoSuchAlgorithmException;

public  class PhoneUtil {

    private static String server = "open.ucpaas.com";

    private static boolean isTest=Boolean.parseBoolean("true");

    private static String sid = "0d290440544c45d93ea7511d627b7192";
    private static String token = "ed554913d94877f368464569d29ac3c1";
    private static String appid = "2fe620845a6b4660aa643eedecc3bc2b";
    private static String templateid = "331367";


    public static StringBuffer getStringBuffer() {
        StringBuffer sb = new StringBuffer("https://");
        sb.append(server).append("/ol/sms");
        return sb;
    }

    public static String sendSms( String param, String mobile,
                          String uid) {

        String result = "";


        try {
            String url = getStringBuffer().append("/sendsms").toString();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sid", sid);
            jsonObject.put("token", token);
            jsonObject.put("appid", appid);
            jsonObject.put("templateid", templateid);
            jsonObject.put("param", param);
            jsonObject.put("mobile", mobile);
            jsonObject.put("uid", uid);

            String body = jsonObject.toJSONString();

            result = postJson(url, body, null);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static String postJson(String url, String body, String charset) {

        String result = null;

        if (isTest) {
            if (null == charset) {
                charset = "UTF-8";
            }
            CloseableHttpClient httpClient = null;
            HttpPost httpPost = null;
            try {
                httpClient = HttpConnectionManager.getInstance().getHttpClient();
                httpPost = new HttpPost(url);

                // 设置连接超时,设置读取超时
                RequestConfig requestConfig = RequestConfig.custom()
                        .setConnectTimeout(10000)
                        .setSocketTimeout(10000)
                        .build();
                httpPost.setConfig(requestConfig);

                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

                // 设置参数
                StringEntity se = new StringEntity(body, "UTF-8");
                httpPost.setEntity(se);
                HttpResponse response = httpClient.execute(httpPost);
                if (response != null) {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        result = EntityUtils.toString(resEntity, charset);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else {
            result = "config.properties中 is_test 属性值为false, 若已正确设置请求值，请设置为true后再次测试";
        }

        return result;
    }

}

 class HttpConnectionManager {

    private PoolingHttpClientConnectionManager cm = null;

    private static HttpConnectionManager connectionManager;

    public static HttpConnectionManager getInstance() {
        if (connectionManager == null) {
            synchronized (HttpConnectionManager.class) {
                if (connectionManager == null) {
                    connectionManager = new HttpConnectionManager();
                    connectionManager.init();
                }
            }
        }
        return connectionManager;
    }

    private void init() {
        LayeredConnectionSocketFactory sslsf = null;
        try {
            sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(20);
    }

    public CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

        return httpClient;
    }
}

